from django.http import HttpResponse
from django.utils import simplejson
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core import serializers
from django.db.models.query import QuerySet
from django.db.models.manager import Manager

from tr.hba.ppba.models import Package

def index(request):
    
    return render_to_response('index.html', {
        'form': "",
    }, context_instance=RequestContext(request))
    
def rgraph(request):
    
    return render_to_response('rgraph.html', {
        'form': "",
    }, context_instance=RequestContext(request))  
    
def hypertree(request):
    
    return render_to_response('hypertree.html', {
        'form': "",
    }, context_instance=RequestContext(request))      
    
def spacetree(request):
    
    return render_to_response('spacetree.html', {
        'form': "",
    }, context_instance=RequestContext(request))     
    
    
def _get_queryset(klass):
    """
    Returns a QuerySet from a Model, Manager, or QuerySet. Created to make
    get_object_or_404 and get_list_or_404 more DRY.
    """
    if isinstance(klass, QuerySet):
        return klass
    elif isinstance(klass, Manager):
        manager = klass
    else:
        manager = klass._default_manager
    return manager.all()
    
def get_object_or_none(klass, *args, **kwargs):
    queryset = _get_queryset(klass)
    try:
        return queryset.get(*args, **kwargs)
    except queryset.model.DoesNotExist:
        return None
    
def make_tree_node(id, node_name):  
    node_name = node_name.strip()  
    
    return {'id': id,
            'name': node_name,
            'children': [],
            'data': []}  

def get_package_deps(package):
    deps = []

    for dependency in package.dependency_package.all():
        deps.append(dependency.dependency) 
        
    return deps
    
    
def make_tree(package, level=1):
    node = make_tree_node(package.id, package.name)
    
    if level > 0: 
        deps = get_package_deps(package)
        [node['children'].append(make_tree(elem, level -1)) for elem in deps]
        
    return node
    
    
    
def get_dependency_tree(request, package):
    
    response_data = None
    
    p = get_object_or_none(Package, name=package)
    
    if p:
        response_data = make_tree(p, level=3)
        
    return HttpResponse(simplejson.dumps(response_data),mimetype='application/json')

def get_description(request, package):
    
    p = get_object_or_none(Package, name=package)
    
    response_data = package
    return HttpResponse(response_data,mimetype='application/json')
